import requests
import os
import re
import urllib.request
import m3u8
import shutil
from Crypto.Cipher import AES
from config import headers
from crawler import prepareCrawl
from merge import mergeMp4
from delete import deleteM3u8, deleteMp4
from cover import getCover
from encode import ffmpegEncode
from args import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def read_urls_from_file(file_path):
    """从文本文件读取URL列表"""
    urls = []
    try:
        with open(file_path, 'r') as f:
            for line in f:
                # 去除两端空白并跳过空行
                cleaned_line = line.strip()
                if cleaned_line and not cleaned_line.startswith('#'):
                    urls.append(cleaned_line)
    except FileNotFoundError:
        print(f"错误：文件 {file_path} 不存在")
    return urls

def download(url):
    encode = 1  # 不轉檔
    target_dir = '/shendu/jable'  # 硬编码绝对路径
    original_cwd = os.getcwd() # 保存初始目錄

    print('准备下载影片: ' + url)
    urlSplit = url.split('/')
    dirName = urlSplit[-2] if urlSplit[-1] == '' else urlSplit[-1]
    
    final_path = os.path.join(target_dir, f'{dirName}.mp4')
    if os.path.exists(final_path):
        print(f'视频 {dirName}.mp4 已存在，跳过下载...')
        return False  # 返回下载状态

    # 创建临时目录
    temp_dir = os.path.join(os.getcwd(), dirName)
    if not os.path.exists(temp_dir):
        os.makedirs(temp_dir)

    try:
        # 配置Selenium
        options = Options()
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        options.add_argument('--disable-extensions')
        options.add_argument('--headless')
        options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36")
        dr = webdriver.Chrome(options=options)
        dr.get(url)
        
        # 提取m3u8链接
        result = re.search("https://.+m3u8", dr.page_source)
        if not result:
            print("未找到m3u8链接")
            return False
        m3u8url = result[0]

        # 获取m3u8文件
        m3u8urlList = m3u8url.split('/')
        m3u8urlList.pop(-1)
        downloadurl = '/'.join(m3u8urlList)
        m3u8file = os.path.join(temp_dir, dirName + '.m3u8')
        urllib.request.urlretrieve(m3u8url, m3u8file)

        # 解析m3u8
        m3u8obj = m3u8.load(m3u8file)
        m3u8uri = ''
        m3u8iv = ''

        # 处理加密密钥
        if m3u8obj.keys and m3u8obj.keys[0]:
            key = m3u8obj.keys[0]
            m3u8uri = key.uri
            m3u8iv = key.iv

        # 构建TS列表
        tsList = [downloadurl + '/' + seg.uri for seg in m3u8obj.segments]

        # 初始化解密器
        cipher = None
        if m3u8uri:
            m3u8keyurl = downloadurl + '/' + m3u8uri
            response = requests.get(m3u8keyurl, headers=headers, timeout=10)
            contentKey = response.content
            iv = m3u8iv.replace("0x", "")[:16].encode() if m3u8iv else b'0'*16
            cipher = AES.new(contentKey, AES.MODE_CBC, iv)

        # 下载并处理片段
        deleteM3u8(temp_dir)
        prepareCrawl(cipher, temp_dir, tsList)
        mergeMp4(temp_dir, tsList)
        deleteMp4(temp_dir)

        # 转码处理
        ffmpegEncode(temp_dir, dirName, encode)

        # 移动最终文件
        temp_file = os.path.join(temp_dir, f'{dirName}.mp4')
        if os.path.exists(temp_file):
            shutil.move(temp_file, final_path)
            print(f'文件已保存至: {final_path}')
            return True
        else:
            print('错误: 转码后未生成视频文件')
            return False

    except Exception as e:
        print(f'处理过程中发生错误: {str(e)}')
        return False
    finally:
        # 清理临时目录
        try:
            os.chdir(original_cwd)
            shutil.rmtree(temp_dir, ignore_errors=True)
        except Exception as e:
            print(f'清理临时目录时出错: {str(e)}')

def main():
    # 从指定文件读取URL列表
    input_file = "output.txt"  # 包含视频链接的文本文件
    urls = read_urls_from_file(input_file)
    
    if not urls:
        print("没有需要处理的链接")
        return

    # 按顺序处理每个链接
    for url in urls:
        print(f"\n{'='*60}")
        
        if download(url):
            print("下载成功，进入下一个链接")
        else:
            print("下载失败，尝试下一个链接")

if __name__ == '__main__':
    main()